package yin.com.controller.login;

import yin.com.constant.Cont;
import yin.com.controller.BaseServlet;
import yin.com.model.User;
import yin.com.service.Userserver;
import yin.com.service.impl.Userserverimpl;
import yin.com.utils.MailUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/long/*")
public class Loginserver extends BaseServlet {
    private Userserver userserver = new Userserverimpl();

    public void loginenter(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String affirm = req.getParameter("affirm");
        if (null != username && null != password) {
            User userne = userserver.findUserByNameAndPwd(username);
            if (userne != null) {
                if (password.equals(userne.getPassword())) {
                    if (null != affirm) {
                        Cookie c = new Cookie("name", username);
                        c.setMaxAge(Cont.MAX_COOK_TIME);
                        c.setPath("/");
                        resp.addCookie(c);
                    }
                    //设置会话域保存用户ID，方便过滤器做登录拦截
                    req.getSession().setAttribute("userId", userne.getId());
                    resp.sendRedirect(req.getContextPath() + "/view/home");
                    return;
                }
            }
        }
        resp.sendRedirect(req.getContextPath() + "/");
    }

    public void twologin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie c : cookies) {
                if ("name".equals(c.getName())) {
                    c.setMaxAge(0);
                    c.setPath("/");
                    resp.addCookie(c);
                    break;
                }
            }
        }
        resp.sendRedirect(req.getContextPath() + "/");
    }


    //注册接口
    public void registuser(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");
        if (checkEmail(email)) {

            if (null != username && null != password) {

                if (password.equals(password2)) {
                    User user = userserver.findUserByNameAndPwd(username);
                    //第一个查询数据库是否有这个用户，有就不能添加
                    if (null != user) {

                        req.getSession().setAttribute("exist", "用户已存在");
                        resp.sendRedirect(req.getContextPath() + "/view/existence");
                    } else {
                        User enailuser = userserver.findUserEmail(email);
                        if (null != enailuser) {
                            req.getSession().setAttribute("exist", "邮箱已存在");
                            resp.sendRedirect(req.getContextPath() + "/view/existence");
                        } else {
                            userserver.adduser(email, username, password);
                            resp.sendRedirect(req.getContextPath() + "/view/index");
                        }
                    }
                } else {
                    req.getSession().setAttribute("exist", "密码不一致");
                    resp.sendRedirect(req.getContextPath() + "/view/existence");
                }
            } else {
                req.getSession().setAttribute("exist", "用户名和密码必填");
                resp.sendRedirect(req.getContextPath() + "/view/existence");
            }
        } else {
            req.getSession().setAttribute("exist", "请输入正确的邮箱");
            resp.sendRedirect(req.getContextPath() + "/view/existence");
        }

    }

    public void sendemain(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.setHeader("content-Type", "text/html");
            String email = req.getParameter("email");
            HttpSession session = req.getSession();
            if (checkEmail(email)) {
                Object obj = session.getAttribute(email);
                if (null == obj) {
                    try {

                        String title = "《小标交友》重置密码";
                        String conde = createRandomNum();
                        String conter = "你发的验证码:" + conde;
                        session.setAttribute(email, conde);
                        session.setMaxInactiveInterval(Cont.MAX_CODE_TIME);
                        MailUtil.send(email, title, conter, MailUtil.UNICODE);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    resp.getWriter().write("验证码发送成功，请查看");
                } else {
                    resp.getWriter().write("验证码已发送您的邮箱了，请查收");
                }

            } else {
                resp.getWriter().write("邮箱格式不对，请重新输入");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void resetPassword(HttpServletRequest req, HttpServletResponse resp) {
        try {

            String email = req.getParameter("email");
            String Code = req.getParameter("emailCode");
            String password = req.getParameter("password");
            HttpSession session = req.getSession();
            if (checkEmail(email)) {
                Object obj = session.getAttribute(email);
                if (null != obj) {
                    String emailCode = obj.toString();
                    if (emailCode.equals(Code)) {
                        User user = userserver.findUserByEmail(email);
                        if (null != user) {
                            userserver.resetPass(user.getId(), password);
                            resp.sendRedirect(req.getContextPath() + "/view/index");
                            return;
                        }
                    }
                }
            }
            req.getSession().setAttribute("forgetErrorMsg", "重置失败");
            resp.sendRedirect(req.getContextPath() + "/view/forget");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static String createRandomNum() {
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        return num + "";
    }

    private boolean checkEmail(String email) {
        if (null == email || "".equals(email)) {
            return false;
        }

        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }

    }


}
